<template>
  <div class="app-container">
    <div class="dashboard-container">
      <!-- 使用卡片容器包装内容 -->
      <div class="main-content-card">
        <div class="search-container">
          <div class="search-header">
            <div class="header-left">
              <i class="el-icon-search header-icon"></i>
              <span class="header-title">商品查询</span>
            </div>
            <div class="header-actions">
              <el-button size="small" icon="el-icon-refresh-left" class="reset-btn" @click="resetQuery">重置</el-button>
              <el-button size="small" type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
              <el-button
                size="small"
                type="text"
                @click="toggleSearchCollapse"
                class="collapse-btn">
                {{ isSearchCollapsed ? '展开' : '收起' }}
                <i :class="isSearchCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
              </el-button>
            </div>
          </div>

          <div class="search-content" :class="{ 'is-collapsed': isSearchCollapsed }">
            <div class="search-row">
              <div class="search-field">
                <label class="field-label">商品名称/条码</label>
                <el-input v-model="queryParams.nameOrBarcode" placeholder="请输入" clearable></el-input>
              </div>
              <div class="search-field">
                <label class="field-label">SPU</label>
                <el-input v-model="queryParams.spu" placeholder="请输入" clearable></el-input>
              </div>
              <div class="search-field">
                <label class="field-label">SKU</label>
                <el-input v-model="queryParams.sku" placeholder="请输入" clearable></el-input>
              </div>
            </div>

            <div class="search-row">
              <div class="search-field">
                <label class="field-label">外部编码</label>
                <el-input v-model="queryParams.outCode" placeholder="请输入" clearable></el-input>
              </div>
              <div class="search-field">
                <label class="field-label">商品类目</label>
                <el-cascader
                  v-model="queryParams.categoryId"
                  placeholder="请选择"
                  clearable></el-cascader>
              </div>
              <div class="search-field">
                <label class="field-label">标签</label>
                <el-select v-model="queryParams.tag" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                </el-select>
              </div>
            </div>

            <div class="search-row">
              <div class="search-field">
                <label class="field-label">渠道类目</label>
                <el-select v-model="queryParams.channelAttr" placeholder="请选择" clearable>
                  <el-option label="请选择" value=""></el-option>
                </el-select>
              </div>
              <div class="search-field">
                <label class="field-label">品牌</label>
                <el-select
                  v-model="queryParams.brand"
                  filterable
                  placeholder="请先选择品牌"
                  clearable>
                  <el-option
                    v-for="item in brand"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                  </el-option>
                </el-select>
              </div>
              <div class="search-field">
                <label class="field-label">审核状态</label>
                <el-select v-model="queryParams.status" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option label="未维护" value="未维护"></el-option>
                </el-select>
              </div>
              <div class="search-field">
                <label class="field-label">商品来源</label>
                <el-select v-model="queryParams.source" placeholder="请输入" clearable>
                  <el-option label="请输入" value="" disabled></el-option>
                </el-select>
              </div>
            </div>

            <div class="search-row checkbox-row" v-show="!isSearchCollapsed">
              <div class="search-field checkbox-field">
                <label class="field-label">其他条件筛选</label>
                <div class="checkbox-container">
                  <el-checkbox v-model="queryParams.imageEmpty">图片为空</el-checkbox>
                  <el-checkbox v-model="queryParams.isStandard">标品</el-checkbox>
                  <el-checkbox v-model="queryParams.noStandardName">无规格名称</el-checkbox>
                  <el-checkbox v-model="queryParams.channelNotSell">渠道不可售</el-checkbox>
                  <el-checkbox v-model="queryParams.noChannelCategory">无美团类目属性</el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="button-container">
          <div class="left-buttons">
            <el-dropdown class="action-dropdown" @command="handleAddCommand">
              <el-button size="medium" type="primary" class="dropdown-btn">
                新增商品 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="single">单个新增商品</el-dropdown-item>
                <el-dropdown-item command="excelMain">Excel新增商品主档</el-dropdown-item>
                <el-dropdown-item command="excelSpec">Excel批量新建规格</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <el-dropdown class="action-dropdown" @command="handleBatchCommand">
              <el-button size="medium" plain class="dropdown-btn">
                批量管理 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="excelModifyMain">Excel修改商品主档</el-dropdown-item>
                <el-dropdown-item command="batchCopyToStore">批量覆盖商品到门店</el-dropdown-item>
                <el-dropdown-item command="batchUploadImage">批量上传/导入商品图片</el-dropdown-item>
                <el-dropdown-item command="batchSetTags">批量设置主档商品标签</el-dropdown-item>
                <el-dropdown-item command="excelModifyCategory">Excel批量修改类目属性</el-dropdown-item>
                <el-dropdown-item command="useChannelInfo">一键使用渠道推荐信息</el-dropdown-item>
                <el-dropdown-item command="batchModifyPrice">批量修改总部零售价</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

          <div class="right-buttons">
            <el-dropdown class="action-dropdown" @command="handleExportCommand">
              <el-button size="medium" plain class="dropdown-btn">
                导出 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="exportSelected">导出选中</el-dropdown-item>
                <el-dropdown-item command="exportAll">导出全部</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>

        <!-- 高级筛选区域 -->
        <div class="filter-section">
          <div class="filter-header">
            <div class="filter-title">
              <i class="el-icon-filter"></i>
              <span>高级筛选</span>
            </div>
            <div class="filter-actions">
              <el-button 
                type="text" 
                class="filter-expand-btn" 
                @click="toggleAdvancedFilter"
              >
                {{ isAdvancedFilterExpanded ? '收起' : '展开' }}
                <i :class="isAdvancedFilterExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </el-button>
            </div>
          </div>
          
          <el-collapse-transition>
            <div v-show="isAdvancedFilterExpanded" class="filter-content">
              <el-form :model="filterForm" ref="filterForm" label-width="100px" size="small" :inline="true">
                <!-- 渠道类目筛选 -->
                <el-form-item label="渠道类目">
                  <el-cascader
                    v-model="filterForm.channelCategory"
                    :options="channelCategoryOptions"
                    :props="{ checkStrictly: true, emitPath: false }"
                    clearable
                    filterable
                    placeholder="请选择渠道类目"
                    class="filter-cascader"
                  ></el-cascader>
                </el-form-item>
                
                <!-- 商品类目筛选 -->
                <el-form-item label="商品类目">
                  <el-cascader
                    v-model="filterForm.productCategory"
                    :options="productCategoryOptions"
                    :props="{ checkStrictly: true, emitPath: false }"
                    clearable
                    filterable
                    placeholder="请选择商品类目"
                    class="filter-cascader"
                  ></el-cascader>
                </el-form-item>
                
                <!-- 商品状态筛选 -->
                <el-form-item label="商品状态">
                  <el-select 
                    v-model="filterForm.status" 
                    placeholder="请选择状态"
                    clearable
                    class="filter-select"
                  >
                    <el-option label="全部" value=""></el-option>
                    <el-option label="已上架" value="1"></el-option>
                    <el-option label="已下架" value="0"></el-option>
                    <el-option label="待审核" value="2"></el-option>
                  </el-select>
                </el-form-item>
                
                <!-- 商品品牌筛选 -->
                <el-form-item label="商品品牌">
                  <el-select 
                    v-model="filterForm.brand" 
                    placeholder="请选择品牌"
                    clearable
                    filterable
                    class="filter-select"
                  >
                    <el-option
                      v-for="item in brandOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                
                <!-- 价格区间筛选 -->
                <el-form-item label="价格区间">
                  <div class="price-range">
                    <el-input-number 
                      v-model="filterForm.minPrice" 
                      :min="0" 
                      :precision="2" 
                      size="small" 
                      controls-position="right"
                      placeholder="最低价"
                      class="price-input"
                    ></el-input-number>
                    <span class="price-separator">-</span>
                    <el-input-number 
                      v-model="filterForm.maxPrice" 
                      :min="0" 
                      :precision="2" 
                      size="small" 
                      controls-position="right"
                      placeholder="最高价"
                      class="price-input"
                    ></el-input-number>
                  </div>
                </el-form-item>
                
                <!-- 是否缺图筛选 -->
                <el-form-item label="是否缺图">
                  <el-radio-group v-model="filterForm.imageEmpty">
                    <el-radio label="">全部</el-radio>
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <!-- 是否标品筛选 -->
                <el-form-item label="是否标品">
                  <el-radio-group v-model="filterForm.isStandard">
                    <el-radio label="">全部</el-radio>
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <!-- 渠道是否售卖 -->
                <el-form-item label="渠道是否售卖">
                  <el-radio-group v-model="filterForm.channelNotSell">
                    <el-radio label="">全部</el-radio>
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
              
              <!-- 应用的筛选标签展示 -->
              <div v-if="hasActiveFilters" class="active-filters">
                <div class="active-filters-title">
                  <i class="el-icon-info"></i>
                  <span>已选筛选条件</span>
                </div>
                <div class="active-filters-content">
                  <el-tag 
                    v-if="filterForm.channelCategory"
                    closable
                    @close="filterForm.channelCategory = null"
                    size="small"
                    effect="plain"
                    type="primary"
                  >
                    渠道类目: {{getChannelCategoryName(filterForm.channelCategory)}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.productCategory"
                    closable
                    @close="filterForm.productCategory = null"
                    size="small"
                    effect="plain"
                    type="success"
                  >
                    商品类目: {{getProductCategoryName(filterForm.productCategory)}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.status"
                    closable
                    @close="filterForm.status = ''"
                    size="small"
                    effect="plain"
                    type="info"
                  >
                    商品状态: {{getStatusName(filterForm.status)}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.brand"
                    closable
                    @close="filterForm.brand = ''"
                    size="small"
                    effect="plain"
                    type="warning"
                  >
                    商品品牌: {{getBrandName(filterForm.brand)}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.minPrice || filterForm.maxPrice"
                    closable
                    @close="clearPriceFilter"
                    size="small"
                    effect="plain"
                    type="danger"
                  >
                    价格区间: {{getPriceRangeText()}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.imageEmpty"
                    closable
                    @close="filterForm.imageEmpty = ''"
                    size="small"
                    effect="plain"
                  >
                    {{filterForm.imageEmpty === '1' ? '缺图商品' : '有图商品'}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.isStandard"
                    closable
                    @close="filterForm.isStandard = ''"
                    size="small"
                    effect="plain"
                  >
                    {{filterForm.isStandard === '1' ? '标准品' : '非标准品'}}
                  </el-tag>
                  <el-tag 
                    v-if="filterForm.channelNotSell !== ''"
                    closable
                    @close="filterForm.channelNotSell = ''"
                    size="small"
                    effect="plain"
                  >
                    {{filterForm.channelNotSell === '1' ? '渠道不售卖' : '渠道可售卖'}}
                  </el-tag>
                </div>
              </div>
              
              <div class="filter-actions-bar">
                <el-button type="primary" icon="el-icon-search" @click="applyFilter">应用筛选</el-button>
                <el-button icon="el-icon-refresh" @click="resetFilter">重置筛选</el-button>
                <div v-if="filterCount > 0" class="filter-summary">
                  已筛选出 <strong>{{filteredTotal}}</strong> 个商品
                </div>
              </div>
            </div>
          </el-collapse-transition>
        </div>

        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="goodsList"
            row-key="id"
            :border="false"
            class="tech-table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" fixed="left" />
            <el-table-column label="主图" align="center" width="120" class-name="image-column">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.mainImage"
                  :src="scope.row.mainImage"
                  fit="cover"
                  class="table-image"
                  :preview-src-list="[scope.row.mainImage]">
                </el-image>
                <div v-else class="image-placeholder">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" min-width="200" show-overflow-tooltip>
              <template slot="header">
                <div class="custom-header">
                  <i class="el-icon-goods header-icon"></i>
                  <span>商品名称</span>
                </div>
              </template>
              <template slot-scope="scope">
                <div class="product-container">
                  <div class="product-name">{{ scope.row.name }}</div>
                  <div class="product-detail">
                    <div class="status-tags">
                      <span v-if="scope.row.isStandard === '标品'" class="status-tag status-success">标品</span>
                      <span v-else class="status-tag status-warning">非标品</span>
                      <span v-if="scope.row.status === '已上架'" class="status-tag status-success">已上架</span>
                      <span v-else-if="scope.row.status === '未维护'" class="status-tag status-warning">未维护</span>
                    </div>
                    <div class="spec-name">{{ scope.row.specification || '默认规格' }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格信息" align="left" min-width="250">
              <template slot="header">
                <div class="custom-header">
                  <i class="el-icon-s-grid header-icon"></i>
                  <span>规格信息</span>
                </div>
              </template>
              <template slot-scope="scope">
                <div v-for="(sku, index) in scope.row.productSkus" :key="index" class="spec-info">
                  <div class="spec-item">
                    <span class="spec-label">规格：</span>
                    <span class="spec-value">{{ sku.specification || '无规格' }}</span>
                  </div>
                  <div class="spec-item">
                    <span class="spec-label">SKU：</span>
                    <span class="spec-value highlight-value">{{ sku.skuCode || '-' }}</span>
                  </div>
                  <div class="spec-item">
                    <span class="spec-label">商品条码：</span>
                    <span class="spec-value">{{ sku.barcode || '-' }}</span>
                  </div>
                  <div class="spec-item">
                    <span class="spec-label">外部编码：</span>
                    <span class="spec-value">{{ sku.externalCode || '-' }}</span>
                  </div>
                  <div v-if="index !== scope.row.productSkus.length - 1" class="spec-divider"></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="渠道信息" align="left" min-width="200">
              <template slot="header">
                <div class="custom-header">
                  <i class="el-icon-connection header-icon"></i>
                  <span>渠道信息</span>
                </div>
              </template>
              <template slot-scope="scope">
                <div class="channel-info">
                  <div v-if="scope.row.meituanChannelLevel1" class="channel-item">
                    <el-tag size="mini" type="warning" class="channel-tag">
                      {{ scope.row.meituanChannelLevel1 }}/{{ scope.row.meituanChannelLevel2 }}/{{ scope.row.meituanChannelLevel3 }}
                    </el-tag>
                  </div>
                  <div v-else class="channel-item">
                    <i class="el-icon-info-circle channel-icon"></i>
                    <span class="channel-empty">暂无渠道信息</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" width="150">
              <template slot="header">
                <div class="custom-header">
                  <i class="el-icon-money header-icon"></i>
                  <span>价格</span>
                </div>
              </template>
              <template slot-scope="scope">
                <div v-if="scope.row.price" class="price-container">
                  <span class="price-value">¥{{ scope.row.price }}</span>
                  <el-link
                    type="primary"
                    icon="el-icon-edit"
                    :underline="false"
                    class="edit-price-btn"
                    @click.stop="handleEditPrice(scope.row)"></el-link>
                </div>

                <div v-else class="price-container">
                  <span class="price-empty">未维护</span>
                  <el-link
                    type="primary"
                    icon="el-icon-edit"
                    :underline="false"
                    class="edit-price-btn"
                    @click.stop="handleEditPrice(scope.row)"></el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="280" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  class="action-btn"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['business:spu:edit']">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  class="action-btn"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['business:spu:remove']">删除</el-button>
                <el-dropdown trigger="click">
                  <el-button size="mini" type="info" icon="el-icon-more" class="action-btn"></el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-price-tag" @click.native="handleSetTags(scope.row)">设置标签</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-document" @click.native="handleLog(scope.row)">查看日志</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList" />

        <!-- 添加或修改商品配置对话框 -->
        <good-form
          :visible.sync="goodFormVisible"
          :is-edit="goodFormIsEdit"
          :good-data="goodFormData"
          @submit="handleGoodFormSubmit"
          @close="handleGoodFormClose" />

        <!-- 修改价格弹窗 -->
        <el-dialog
          title="修改价格"
          :visible.sync="priceDialogVisible"
          width="700px"
          append-to-body
          custom-class="price-edit-dialog">
          <div class="price-edit-content">
            <div class="price-table-header">
              <!-- 商品信息 -->
              <div class="price-product-info">
                <div class="price-product-name">{{ priceForm.name }}</div>
                <div class="price-product-specs">规格：{{ priceForm.specification }} | 条码：{{ priceForm.barcode }}</div>
              </div>
              <div class="price-input-wrapper">
                <el-input-number
                  v-model="priceForm.price"
                  size="small"
                  placeholder="0"
                  :min="1"
                  class="price-input"
                  controls-position="right"></el-input-number>
                <span class="price-unit">元</span>
              </div>
            </div>

            <div class="sync-section">
              <div class="sync-label">同步更新：</div>
              <div class="radio-group">
                <div class="radio1">
                  <el-radio v-model="priceForm.syncType" :label="1">
                    <span class="radio-text">商品已覆盖的门店</span>
                  </el-radio>
                  <div class="store-select-section" v-if="priceForm.syncType === 1">
                    <div class="store-note">如门店商品有美补活动则不会修改门店商品价格。</div>
                  </div>
                </div>

                <div>
                  <el-radio v-model="priceForm.syncType" :label="2">
                    <span class="radio-text">指定门店</span>
                  </el-radio>
                  <div class="store-select-section" v-if="priceForm.syncType === 2">
                    <div class="store-note">如门店商品有美补活动则不会修改门店商品价格。</div>
                    <el-select size="small" v-model="priceForm.selectedStores" placeholder="请选择门店" class="store-select">
                      <el-option label="请选择门店" value="" disabled></el-option>
                    </el-select>
                  </div>
                </div>

              </div>

            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="priceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPriceForm">确定</el-button>
          </div>
        </el-dialog>

        <!-- 设置标签弹窗 -->
        <el-dialog title="设置标签" :visible.sync="tagsDialogVisible" width="1200px" append-to-body>
          <div class="tags-dialog-content">
            <el-tabs v-model="tagsActiveTab">
              <el-tab-pane :label="spuTabLabel" name="spu">
                <div class="tags-content-layout">
                  <div class="tags-left-categories">
                    <div class="category-item" :class="{ active: activeCategory === 'all' }"
                      @click="setActiveCategory('all')">
                      <span>全部类型</span>
                    </div>
                    <div class="category-item" :class="{ active: activeCategory === 'level' }"
                      @click="setActiveCategory('level')">
                      <span>商品等级 (4)</span>
                    </div>
                  </div>

                  <div class="tags-right-content">
                    <div class="tags-search-container">
                      <el-input placeholder="支持关键字模糊搜索" v-model="spuTagsSearch" @input="filterSpuTags"
                        class="tags-search-input">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                      </el-input>
                    </div>

                    <div class="tags-category-container">
                      <div class="tags-category-header">
                        <div class="tags-category-title">商品等级</div>
                        <el-checkbox v-model="spuAllSelected" @change="handleSelectAll('spu')">全选</el-checkbox>
                      </div>
                      <div class="tags-options">
                        <el-checkbox v-if="filteredSpuOptions.S" v-model="spuTagsOptions.S"
                          @change="handleTagChange('S', 'spu')">S</el-checkbox>
                        <el-checkbox v-if="filteredSpuOptions.A" v-model="spuTagsOptions.A"
                          @change="handleTagChange('A', 'spu')">A</el-checkbox>
                        <el-checkbox v-if="filteredSpuOptions.B" v-model="spuTagsOptions.B"
                          @change="handleTagChange('B', 'spu')">B</el-checkbox>
                        <el-checkbox v-if="filteredSpuOptions.C" v-model="spuTagsOptions.C"
                          @change="handleTagChange('C', 'spu')">C</el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane :label="specTabLabel" name="spec">
                <div class="tags-content-layout">
                  <div class="tags-left-categories">
                    <div class="category-item" :class="{ active: activeSpecCategory === 'all' }"
                      @click="setActiveSpecCategory('all')">
                      <span>全部类型</span>
                    </div>
                    <div class="category-item" :class="{ active: activeSpecCategory === 'level' }"
                      @click="setActiveSpecCategory('level')">
                      <span>商品等级 (4)</span>
                    </div>
                  </div>

                  <div class="tags-right-content">
                    <div class="tags-search-container">
                      <el-input placeholder="支持关键字模糊搜索" v-model="specTagsSearch" @input="filterSpecTags"
                        class="tags-search-input">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                      </el-input>
                    </div>

                    <div class="tags-category-container">
                      <div class="tags-category-header">
                        <div class="tags-category-title">商品等级</div>
                        <el-checkbox v-model="specAllSelected" @change="handleSelectAll('spec')">全选</el-checkbox>
                      </div>
                      <div class="tags-options">
                        <el-checkbox v-if="filteredSpecOptions.S" v-model="specTagsOptions.S"
                          @change="handleTagChange('S', 'spec')">S</el-checkbox>
                        <el-checkbox v-if="filteredSpecOptions.A" v-model="specTagsOptions.A"
                          @change="handleTagChange('A', 'spec')">A</el-checkbox>
                        <el-checkbox v-if="filteredSpecOptions.B" v-model="specTagsOptions.B"
                          @change="handleTagChange('B', 'spec')">B</el-checkbox>
                        <el-checkbox v-if="filteredSpecOptions.C" v-model="specTagsOptions.C"
                          @change="handleTagChange('C', 'spec')">C</el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>

            <div class="tags-selected-container">
              <div style="padding-top: 53px; padding-bottom: 18px;">
                <el-input placeholder="搜索已选标签" v-model="selectedTagsSearch" class="tags-search-input">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </div>
              <div class="tags-selected-title">已选标签 ({{ currentTabTags.length }})</div>

              <div v-if="currentTabTags.length === 0" class="tags-selected-empty">
                <img src="@/assets/images/empty-image.png" class="empty-image" alt="暂无数据">
                <p>请从左侧选择标签</p>
              </div>
              <div v-else class="selected-tags-list">
                <div v-for="(tag, index) in filteredSelectedTags" :key="index" class="selected-tag">
                  <span>{{ tag.value }}</span>
                  <i class="el-icon-close" @click="removeTag(tag)"></i>
                </div>
              </div>
            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="tagsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitTagsForm">确定</el-button>
          </div>
        </el-dialog>

        <!-- 操作日志弹窗 -->
        <el-dialog title="操作日志" :visible.sync="logDialogVisible" width="1000px" append-to-body>
          <div class="log-dialog-content">
            <div class="log-header">
              <div class="log-product-info">
                <div v-if="currentLogRow">
                  <div>{{ currentLogRow.name }}</div>
                  <div>SPU: {{ currentLogRow.spu }}</div>
                </div>
              </div>

              <div class="log-filter">
                <el-select v-model="logTypeFilter" placeholder="全部类型" clearable style="width: 150px; margin-right: 10px;">
                  <el-option label="全部类型" value=""></el-option>
                  <el-option label="新增" value="新增"></el-option>
                  <el-option label="修改" value="修改"></el-option>
                  <el-option label="删除" value="删除"></el-option>
                </el-select>

                <el-select v-model="logEntryFilter" placeholder="全部入口" clearable style="width: 150px; margin-right: 10px;">
                  <el-option label="全部入口" value=""></el-option>
                  <el-option label="牛牛花" value="牛牛花"></el-option>
                </el-select>

                <el-date-picker v-model="logDateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 320px;">
                </el-date-picker>
              </div>
            </div>

            <el-table :data="logData" style="width: 100%" border>
              <el-table-column prop="operationType" label="操作类型" width="120" align="center"></el-table-column>
              <el-table-column prop="operationContent" label="操作内容" min-width="250" align="left"></el-table-column>
              <el-table-column prop="operationEntry" label="操作入口" width="150" align="center"></el-table-column>
              <el-table-column prop="operationTime" label="操作时间" width="180" align="center"></el-table-column>
              <el-table-column prop="operator" label="操作人" width="150" align="center"></el-table-column>
            </el-table>

            <pagination v-show="logTotal > 0" :total="logTotal" :page.sync="logQueryParams.pageNum"
              :limit.sync="logQueryParams.pageSize" @pagination="getLogList" />
          </div>
        </el-dialog>

        <!-- Excel新增商品主档弹窗 -->
        <excel-upload :visible.sync="excelMainVisible" title="Excel新增商品主档" type="main"
          @upload-success="handleExcelUploadSuccess" />

        <!-- Excel批量新建规格弹窗 -->
        <excel-upload :visible.sync="excelSpecVisible" title="Excel批量新建规格" type="spec"
          @upload-success="handleExcelUploadSuccess" />
      </div>
    </div>
  </div>
</template>

<script>
import GoodForm from './components/GoodForm.vue';
import ExcelUpload from './components/ExcelUpload.vue';
import { listSpu, getSpu, delSpu, addSpu, updateSpu } from "@/api/business/spu";
export default {
  name: "Goods",
  dicts: ['sys_normal_disable'],
  components: {
    GoodForm,
    ExcelUpload
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 704,
      // 当前激活的标签页
      activeTab: 'all',
      goodsList: [],
      // 商品表格数据
      // goodsList: [
      //   {
      //     id: 1,
      //     name: "MINSHZEE名希之海空胸红防水防汗粉质细腻易上色胭脂茶渍实脱红盘/个",
      //     image: "",
      //     spu: "190032687402713916",
      //     sku: "190032741143925555",
      //     specSize: "644(250克(g) / 个)",
      //     barcode: "-",
      //     outCode: "-",
      //     category: "未分类",
      //     price: "",
      //     status: "未维护",
      //     channelInfo: "服饰鞋包>男装>男士T恤",
      //     storeCoverage: "0/1"
      //   },
      //   {
      //     id: 2,
      //     name: "新款潮仿珍珠耳钉 925银针女ins轻奢高级感复古气质耳饰耳环 1对",
      //     image: "",
      //     spu: "190032687394753743",
      //     sku: "190032741142730759",
      //     specSize: "83(250克(g) / 对)",
      //     barcode: "-",
      //     outCode: "-",
      //     category: "未分类",
      //     price: "",
      //     status: "未维护",
      //     channelInfo: "服饰鞋包>男装>男士T恤",
      //     storeCoverage: "0/1"
      //   },
      //   {
      //     id: 3,
      //     name: "可口可乐 经典美味畅爽 带劲汽水 330毫升*6罐/包",
      //     image: "",
      //     spu: "189579781588462395",
      //     sku: "189579788143736017",
      //     specSize: "(1400毫升(ml) / 瓶)",
      //     barcode: "6908512208881",
      //     outCode: "-",
      //     category: "未分类",
      //     price: "6.5",
      //     channelInfo: "饮品>饮料>碳酸饮料",
      //     storeCoverage: "0/1"
      //   },
      //   {
      //     id: 4,
      //     name: "超威 艾草清香型蚊香 145克/盒",
      //     image: "",
      //     spu: "189579781580493212",
      //     sku: "189579788143736832",
      //     specSize: "(145克(g) / 盒)",
      //     barcode: "6920174751000",
      //     outCode: "-",
      //     category: "未分类",
      //     price: "6.5",
      //     channelInfo: "家庭清洁>家用芳香剂/驱虫>驱蚊杀虫",
      //     storeCoverage: "0/1"
      //   }
      // ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        isStandard: '',
        barcode: '',
        spu: '',
        sku: '',
        outCode: '',
        category: '',
        tags: '',
        meituan: '',
        channelAttr: '',
        brand: '',
        status:'' ,
        source: '',
        imageEmpty: '',
        isStandard: '',
        noStandardName: '',
        channelNotSell:'' ,
        noChannelCategory: ''
      },
      // 表单参数
      form: {
        isStandard: 1,
        attributes: {} // 确保是对象形式
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        barcode: [
          { required: true, message: "商品条码不能为空", trigger: "blur" }
        ],
        outCode: [
          { required: true, message: "外部编码不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "商品类目不能为空", trigger: "blur" }
        ],
        brand: [
          { required: true, message: "品牌不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "审核状态不能为空", trigger: "blur" }
        ]
      },
      // 添加价格修改相关数据
      priceDialogVisible: false,
      priceForm: {
        id: undefined,
        name: '',
        barcode: '',
        price: 0
      },
      // 新增商品表单相关数据
      goodFormVisible: false,
      goodFormIsEdit: false,
      goodFormData: {},
      // 设置标签相关数据
      tagsDialogVisible: false,
      tagsActiveTab: 'spu',
      currentTagsRow: null,
      spuTagsSearch: '',
      specTagsSearch: '',
      selectedTagsSearch: '',
      filteredSpuOptions: {
        S: true,
        A: true,
        B: true,
        C: true
      },
      filteredSpecOptions: {
        S: true,
        A: true,
        B: true,
        C: true
      },
      selectedTags: [],
      spuTagsOptions: {
        S: false,
        A: false,
        B: false,
        C: false
      },
      specTagsOptions: {
        S: false,
        A: false,
        B: false,
        C: false
      },
      spuAllSelected: false,
      specAllSelected: false,
      activeCategory: 'all',
      activeSpecCategory: 'all',
      // 查看日志相关数据
      logDialogVisible: false,
      currentLogRow: null,
      logData: [],
      logQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      logTotal: 2,
      logTypeFilter: '',
      logEntryFilter: '',
      logDateRange: [],
      // Excel上传相关数据
      excelMainVisible: false,
      excelSpecVisible: false,
      brand: [], //品牌
      unitsGood: [], //货品单位
      weight: [], //重量
      // 添加搜索区域折叠状态
      isSearchCollapsed: false,
      // 高级筛选相关数据
      isAdvancedFilterExpanded: false,
      filterForm: {
        channelCategory: null,
        productCategory: null,
        status: '',
        brand: '',
        minPrice: 0,
        maxPrice: 0,
        imageEmpty: '',
        isStandard: '',
        channelNotSell: ''
      },
      channelCategoryOptions: [],
      productCategoryOptions: [],
      brandOptions: [],
      filterCount: 0,
      filteredTotal: 0
    };
  },
  created() {
    // 初始化时不需要调用API，直接使用模拟数据
    this.loading = false;
    // 品牌
    this.getDicts('brand').then(res => {
      this.brand = res.data
    })
    // 加载渠道类目和商品类目数据
    this.loadFilterOptions();
    this.getList()
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = false;
      listSpu(this.queryParams).then(response => {
        this.goodsList = response.rows
        this.total = response.total
      })
    },
    /** 切换标签页 */
    handleTabClick(tab) {
      this.$message.success(`切换到${tab.label}`);
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增商品按钮操作 */
    handleAddCommand(command) {
      // First force close any open dialog
      this.goodFormVisible = false;
      
      // Clear state
      this.goodFormIsEdit = false;
      this.goodFormData = {};
      
      // Delay opening to avoid race conditions with Vue's reactivity
      setTimeout(() => {
        switch (command) {
          case "single":
            this.goodFormVisible = true;
            break;
          case "excelMain":
            this.excelMainVisible = true;
            break;
          case "excelSpec":
            this.excelSpecVisible = true;
            break;
          default:
            break;
        }
      }, 100);
    },
    /** 修改商品按钮操作 */
    handleUpdate(row) {
      // First force close any open dialog
      this.goodFormVisible = false;
      
      // Clear state
      this.goodFormData = {};
      
      // Delay opening to ensure dialog is actually closed first
      setTimeout(() => {
        this.goodFormIsEdit = true;
        this.goodFormData = JSON.parse(JSON.stringify(row));
        this.goodFormVisible = true;
      }, 100);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
      this.$message.success("搜索操作执行成功");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$message.success("重置操作执行成功");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除商品"' + row.name + '"？').then(() => {
        this.$message.success("删除成功");
        // 从列表中移除该商品
        const index = this.goodsList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.goodsList.splice(index, 1);
          this.total--;
        }
      }).catch(() => { });
    },
    /** 设置标签操作 */
    handleSetTags(row) {
      this.currentTagsRow = row;
      this.tagsDialogVisible = true;
    },
    /** 查看日志操作 */
    handleLog(row) {
      this.logDialogVisible = true;
      this.currentLogRow = row;
      // 这里可以调用API获取日志数据
      // 模拟日志数据
      this.logData = [
        {
          operationType: '新增',
          operationContent: '新增',
          operationEntry: '牛牛花',
          operationTime: '2025.03.14 07:25:28',
          operator: 'fnlyn3'
        },
        {
          operationType: '修改',
          operationContent: '[规格:447]新建',
          operationEntry: '牛牛花',
          operationTime: '2025.03.14 07:25:28',
          operator: 'fnlyn3'
        }
      ];
    },
    /** 批量管理下拉菜单操作 */
    handleBatchCommand(command) {
      switch (command) {
        case "excelModifyMain":
          this.$message.success("Excel修改商品主档功能");
          break;
        case "batchCopyToStore":
          this.$message.success("批量覆盖商品到门店功能");
          break;
        case "batchUploadImage":
          this.$message.success("批量上传/导入商品图片功能");
          break;
        case "batchSetTags":
          this.$message.success("批量设置主档商品标签功能");
          break;
        case "excelModifyCategory":
          this.$message.success("Excel批量修改类目属性功能");
          break;
        case "useChannelInfo":
          this.$message.success("一键使用渠道推荐信息功能");
          break;
        case "batchModifyPrice":
          this.$message.success("批量修改总部零售价功能");
          break;
        default:
          break;
      }
    },
    /** 导出下拉菜单操作 */
    handleExportCommand(command) {
      switch (command) {
        case "exportSelected":
          this.$message.success("导出选中商品功能");
          break;
        case "exportAll":
          this.$message.success("导出全部商品功能");
          break;
        default:
          break;
      }
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('提交的表单', valid);
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
        }
      });
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        barcode: undefined,
        outCode: undefined,
        category: undefined,
        brand: undefined,
        status: undefined,
        description: undefined
      };
      this.resetForm("form");
    },
    /** 修改价格按钮操作 */
    handleEditPrice(row) {
      this.priceForm = {
        id: row.id,
        name: row.name,
        barcode: row.barcode || '',
        price: parseFloat(row.price) || 0
      };
      this.priceDialogVisible = true;
    },
    /** 提交价格表单 */
    submitPriceForm() {
      // 这里可以调用API保存价格
      // 模拟保存成功
      const index = this.goodsList.findIndex(item => item.id === this.priceForm.id);
      if (index !== -1) {
        this.goodsList[index].price = this.priceForm.price.toFixed(2);
        this.goodsList[index].status = ''; // 更新状态
      }

      this.$message.success("价格修改成功");
      this.priceDialogVisible = false;
    },
    /** 处理新增商品表单提交 */
    handleGoodFormSubmit(spuData) {
      spuData.attributes = JSON.stringify(spuData.attributes);
      spuData.mainImage = spuData.mainImage.map(img => img.url).join(",");
      spuData.mainImageTwo = spuData.mainImageTwo.map(img => img.url).join(",");
      spuData.mainImageThree = spuData.mainImageThree.map(img => img.url).join(",");
      
      if (spuData.id) {
        // **更新商品**
        updateSpu(spuData).then(res => {
          this.$message.success("商品更新成功");
          
          // Force close dialog
          this.goodFormVisible = false;
          
          // Reset state with delay
          setTimeout(() => {
            this.goodFormIsEdit = false;
            this.goodFormData = {};
            this.getList(); // 刷新商品列表
          }, 200);
        }).catch(err => {
          console.error("商品更新失败:", err);
          this.$message.error("商品更新失败，请稍后重试");
        });
      } else {
        // **新增商品**
        addSpu(spuData).then(res => {
          this.$message.success("商品提交成功");
          
          // Force close dialog
          this.goodFormVisible = false;
          
          // Reset state with delay
          setTimeout(() => {
            this.goodFormIsEdit = false;
            this.goodFormData = {};
            this.getList(); // 刷新商品列表
          }, 200);
        }).catch(err => {
          console.error("商品提交失败:", err);
          this.$message.error("商品提交失败，请稍后重试");
        });
      }
    },
    /** 处理商品表单关闭 */
    handleGoodFormClose() {
      // Force dialog to close immediately
      this.goodFormVisible = false;
      
      // Reset form state with slight delay
      setTimeout(() => {
        this.goodFormIsEdit = false;
        this.goodFormData = {};
      }, 200);
    },
    /** 提交标签表单 */
    submitTagsForm() {
      this.$message.success("标签设置成功");
      this.tagsDialogVisible = false;
    },
    /** 设置当前活动分类 */
    setActiveCategory(category) {
      this.activeCategory = category;
    },
    /** 设置当前活动规格分类 */
    setActiveSpecCategory(category) {
      this.activeSpecCategory = category;
    },
    /** 处理标签变化 */
    handleTagChange(tag, type) {
      const isSelected = type === 'spu' ? this.spuTagsOptions[tag] : this.specTagsOptions[tag];

      if (isSelected) {
        // 添加标签
        this.selectedTags.push({
          type: type,
          value: tag,
          category: '商品等级'
        });
      } else {
        // 移除标签
        const index = this.selectedTags.findIndex(item => item.type === type && item.value === tag);
        if (index !== -1) {
          this.selectedTags.splice(index, 1);
        }
      }

      // 更新标签页标题中的数量
      this.updateTabLabels();
    },
    /** 处理全选 */
    handleSelectAll(type) {
      const options = type === 'spu' ? this.spuTagsOptions : this.specTagsOptions;
      const isSelected = type === 'spu' ? this.spuAllSelected : this.specAllSelected;

      // 设置所有选项
      for (const key in options) {
        if (options.hasOwnProperty(key)) {
          if (options[key] !== isSelected) {
            options[key] = isSelected;
            this.handleTagChange(key, type);
          }
        }
      }
    },
    /** 移除标签 */
    removeTag(tag) {
      // 从已选标签中移除
      const index = this.selectedTags.findIndex(item =>
        item.type === tag.type && item.value === tag.value
      );

      if (index !== -1) {
        this.selectedTags.splice(index, 1);
      }

      // 更新对应的复选框状态
      if (tag.type === 'spu') {
        this.spuTagsOptions[tag.value] = false;
      } else {
        this.specTagsOptions[tag.value] = false;
      }

      // 更新标签页标题中的数量
      this.updateTabLabels();
    },
    /** 更新标签页标题中的数量 */
    updateTabLabels() {
      // 这里不需要做任何事情，因为我们使用计算属性来显示标签数量
    },
    /** 过滤SPU标签 */
    filterSpuTags() {
      const search = this.spuTagsSearch.toLowerCase();
      if (!search) {
        // 如果搜索为空，显示所有选项
        for (const key in this.filteredSpuOptions) {
          this.filteredSpuOptions[key] = true;
        }
        return;
      }

      // 根据搜索关键字过滤选项
      for (const key in this.filteredSpuOptions) {
        this.filteredSpuOptions[key] = key.toLowerCase().includes(search);
      }
    },
    /** 过滤规格标签 */
    filterSpecTags() {
      const search = this.specTagsSearch.toLowerCase();
      if (!search) {
        // 如果搜索为空，显示所有选项
        for (const key in this.filteredSpecOptions) {
          this.filteredSpecOptions[key] = true;
        }
        return;
      }

      // 根据搜索关键字过滤选项
      for (const key in this.filteredSpecOptions) {
        this.filteredSpecOptions[key] = key.toLowerCase().includes(search);
      }
    },
    /** 获取日志列表 */
    getLogList() {
      // 这里可以调用API获取日志数据
      // 模拟API调用
      console.log('获取日志列表，参数：', {
        ...this.logQueryParams,
        type: this.logTypeFilter,
        entry: this.logEntryFilter,
        startDate: this.logDateRange && this.logDateRange.length > 0 ? this.logDateRange[0] : null,
        endDate: this.logDateRange && this.logDateRange.length > 0 ? this.logDateRange[1] : null
      });
    },
    /** 处理Excel上传成功 */
    handleExcelUploadSuccess(data) {
      // console.log('Excel上传成功', data);
      // 这里可以根据需要处理上传成功后的逻辑
      // if (data.type === 'main') {
      //   this.$message.success(`Excel新增商品主档上传成功，构建方式：${data.buildType === 1 ? '仅在主档新建' : '在主档新建并同步到门店'}`);
      // } else {
      //   this.$message.success(`Excel批量新建规格上传成功，构建方式：${data.buildType === 1 ? '仅在主档新建' : '在主档新建并同步到门店'}`);
      // }
    },
    /** 切换搜索区域折叠状态 */
    toggleSearchCollapse() {
      this.isSearchCollapsed = !this.isSearchCollapsed;
    },
    /** 切换高级筛选区域折叠状态 */
    toggleAdvancedFilter() {
      this.isAdvancedFilterExpanded = !this.isAdvancedFilterExpanded;
      
      // 首次展开时，加载类目和品牌数据
      if (this.isAdvancedFilterExpanded && this.channelCategoryOptions.length === 0) {
        this.loadFilterOptions();
      }
    },
    /** 加载筛选选项数据 */
    loadFilterOptions() {
      // 加载渠道类目
      this.loadChannelCategories();
      
      // 加载商品类目
      this.loadProductCategories();
      
      // 加载品牌选项
      this.loadBrandOptions();
    },
    /** 加载渠道类目数据 */
    loadChannelCategories() {
      // 这里应调用实际的API，这里使用模拟数据
      this.channelCategoryOptions = [
        {
          value: 'channel1',
          label: '食品饮料',
          children: [
            { value: 'channel1-1', label: '酒水饮料' },
            { value: 'channel1-2', label: '休闲食品' },
            { value: 'channel1-3', label: '粮油调味' }
          ]
        },
        {
          value: 'channel2',
          label: '日用百货',
          children: [
            { value: 'channel2-1', label: '纸品湿巾' },
            { value: 'channel2-2', label: '家居清洁' }
          ]
        },
        {
          value: 'channel3',
          label: '个人护理',
          children: [
            { value: 'channel3-1', label: '洗发护发' },
            { value: 'channel3-2', label: '口腔护理' }
          ]
        }
      ];
      
      // 构建渠道类目ID到名称的映射
      this.buildChannelCategoryMap(this.channelCategoryOptions);
    },
    /** 加载商品类目数据 */
    loadProductCategories() {
      // 这里应调用实际的API，这里使用模拟数据
      this.productCategoryOptions = [
        {
          value: 'product1',
          label: '食品',
          children: [
            { value: 'product1-1', label: '零食' },
            { value: 'product1-2', label: '饮料' },
            { value: 'product1-3', label: '调味品' }
          ]
        },
        {
          value: 'product2',
          label: '日化',
          children: [
            { value: 'product2-1', label: '洗护' },
            { value: 'product2-2', label: '清洁' }
          ]
        }
      ];
      
      // 构建商品类目ID到名称的映射
      this.buildProductCategoryMap(this.productCategoryOptions);
    },
    /** 加载品牌选项数据 */
    loadBrandOptions() {
      // 这里应调用实际的API，这里使用模拟数据
      this.brandOptions = [
        { value: 'brand1', label: '可口可乐' },
        { value: 'brand2', label: '百事可乐' },
        { value: 'brand3', label: '康师傅' },
        { value: 'brand4', label: '统一' },
        { value: 'brand5', label: '伊利' },
        { value: 'brand6', label: '蒙牛' }
      ];
      
      // 构建品牌ID到名称的映射
      this.buildBrandMap(this.brandOptions);
    },
    /** 构建渠道类目映射 */
    buildChannelCategoryMap(categories) {
      this.channelCategoryMap = {};
      
      const traverse = (items) => {
        items.forEach(item => {
          this.channelCategoryMap[item.value] = item.label;
          if (item.children && item.children.length > 0) {
            traverse(item.children);
          }
        });
      };
      
      traverse(categories);
    },
    /** 构建商品类目映射 */
    buildProductCategoryMap(categories) {
      this.productCategoryMap = {};
      
      const traverse = (items) => {
        items.forEach(item => {
          this.productCategoryMap[item.value] = item.label;
          if (item.children && item.children.length > 0) {
            traverse(item.children);
          }
        });
      };
      
      traverse(categories);
    },
    /** 构建品牌映射 */
    buildBrandMap(brands) {
      this.brandMap = {};
      brands.forEach(brand => {
        this.brandMap[brand.value] = brand.label;
      });
    },
    /** 获取渠道类目名称 */
    getChannelCategoryName(category) {
      return this.channelCategoryMap?.[category] || category;
    },
    /** 获取商品类目名称 */
    getProductCategoryName(category) {
      return this.productCategoryMap?.[category] || category;
    },
    /** 获取品牌名称 */
    getBrandName(brand) {
      return this.brandMap?.[brand] || brand;
    },
    /** 获取价格范围文本 */
    getPriceRangeText() {
      if (this.filterForm.minPrice > 0 && this.filterForm.maxPrice > 0) {
        return `¥${this.filterForm.minPrice} - ¥${this.filterForm.maxPrice}`;
      } else if (this.filterForm.minPrice > 0) {
        return `≥ ¥${this.filterForm.minPrice}`;
      } else if (this.filterForm.maxPrice > 0) {
        return `≤ ¥${this.filterForm.maxPrice}`;
      }
      return '';
    },
    /** 获取状态名称 */
    getStatusName(status) {
      const statusMap = {
        '0': '已下架',
        '1': '已上架',
        '2': '待审核'
      };
      return statusMap[status] || status;
    },
    /** 应用筛选 */
    applyFilter() {
      // 记录筛选条件
      this.queryParams = {
        ...this.queryParams,
        channelCategory: this.filterForm.channelCategory,
        productCategory: this.filterForm.productCategory,
        status: this.filterForm.status,
        brand: this.filterForm.brand,
        minPrice: this.filterForm.minPrice > 0 ? this.filterForm.minPrice : undefined,
        maxPrice: this.filterForm.maxPrice > 0 ? this.filterForm.maxPrice : undefined,
        imageEmpty: this.filterForm.imageEmpty,
        isStandard: this.filterForm.isStandard,
        channelNotSell: this.filterForm.channelNotSell
      };
      
      // 获取筛选后的数据
      this.getList();
      
      // 计算筛选结果数量（这里应该来自API返回的数据）
      this.filteredTotal = Math.floor(Math.random() * 500) + 50;
      
      this.$message.success('筛选条件已应用');
    },
    /** 清除价格筛选 */
    clearPriceFilter() {
      this.filterForm.minPrice = 0;
      this.filterForm.maxPrice = 0;
    },
    /** 重置筛选 */
    resetFilter() {
      this.filterForm = {
        channelCategory: null,
        productCategory: null,
        status: '',
        brand: '',
        minPrice: 0,
        maxPrice: 0,
        imageEmpty: '',
        isStandard: '',
        channelNotSell: ''
      };
      
      // 重置查询参数中的筛选条件
      this.queryParams = {
        ...this.queryParams,
        channelCategory: undefined,
        productCategory: undefined,
        status: undefined,
        brand: undefined,
        minPrice: undefined,
        maxPrice: undefined,
        imageEmpty: undefined,
        isStandard: undefined,
        channelNotSell: undefined
      };
      
      // 刷新商品列表
      this.getList();
      
      // 重置筛选结果数量
      this.filteredTotal = 0;
      
      this.$message.success('筛选条件已重置');
    }
  },
  computed: {
    spuTabLabel() {
      const count = this.selectedTags.filter(tag => tag.type === 'spu').length;
      return `SPU标签 (${count})`;
    },
    specTabLabel() {
      const count = this.selectedTags.filter(tag => tag.type === 'spec').length;
      return `"206(250克(g) / 个)"标签 (${count})`;
    },
    currentTabTags() {
      return this.selectedTags.filter(tag => tag.type === this.tagsActiveTab);
    },
    filteredSelectedTags() {
      if (!this.selectedTagsSearch) {
        return this.currentTabTags;
      }
      const search = this.selectedTagsSearch.toLowerCase();
      return this.currentTabTags.filter(tag =>
        tag.value.toLowerCase().includes(search) ||
        tag.category.toLowerCase().includes(search)
      );
    },
    /** 计算已选筛选条件数量 */
    filterCount() {
      let count = 0;
      
      if (this.filterForm.channelCategory) count++;
      if (this.filterForm.productCategory) count++;
      if (this.filterForm.status) count++;
      if (this.filterForm.brand) count++;
      if (this.filterForm.minPrice > 0 || this.filterForm.maxPrice > 0) count++;
      if (this.filterForm.imageEmpty) count++;
      if (this.filterForm.isStandard) count++;
      if (this.filterForm.channelNotSell !== '') count++;
      
      return count;
    },
    /** 计算筛选后的商品总数 */
    filteredTotal() {
      // 实现计算筛选后的商品总数的逻辑
    },
    /** 计算是否有活动筛选 */
    hasActiveFilters() {
      return this.filterCount > 0;
    }
  }
};
</script>

<style scoped>
/* 全局变量 */
:root {
  --primary-color: #409EFF;
  --primary-light: #b3d8ff;
  --primary-lighter: #ecf5ff;
  --primary-dark: #337ecc;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-color: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #C0C4CC;
  --border-color: #DCDFE6;
  --border-light: #E4E7ED;
  --bg-color: #F5F7FA;
  --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  --transition-time: 0.3s;
}

.app-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 50px);
}

.dashboard-container {
  width: 100%;
}

.main-content-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: var(--card-shadow);
  overflow: hidden;
  margin-bottom: 20px;
}

/* 搜索区域 */
.search-container {
  width: 100%;
  margin-bottom: 20px;
  background: linear-gradient(to bottom, #fff, #f8faff);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e8eaec;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #4776e6, #8e54e9);
  color: white;
  border-bottom: 1px solid #e1e6ef;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 20px;
  margin-right: 10px;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px;
  border-radius: 8px;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.reset-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  transition: all 0.3s;
}

.reset-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  color: white;
}

.collapse-btn {
  color: white;
  font-size: 14px;
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.collapse-btn i {
  margin-left: 5px;
  transition: transform 0.3s;
}

.search-content {
  padding: 20px;
  max-height: 500px;
  transition: max-height 0.3s, padding 0.3s;
  overflow: hidden;
}

.search-content.is-collapsed {
  max-height: 100px;
  padding: 20px 20px 0;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  gap: 15px;
}

.search-field {
  flex: 1;
  min-width: 280px;
  display: flex;
  align-items: center;
}

.field-label {
  min-width: 120px;
  text-align: right;
  padding-right: 12px;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
  position: relative;
}

.checkbox-row {
  border-top: 1px dashed #e1e6ef;
  padding-top: 15px;
  margin-top: 5px;
}

.checkbox-field {
  display: flex;
  flex-basis: 100%;
  align-items: flex-start;
}

.checkbox-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.checkbox-container .el-checkbox {
  margin-right: 0;
}

/* 美化输入控件 */
::v-deep .el-select,
::v-deep .el-cascader,
::v-deep .el-input {
  width: 100%;
}

::v-deep .el-input__inner,
::v-deep .el-cascader__label {
  border-radius: 6px;
  transition: all 0.3s;
  height: 36px;
  line-height: 36px;
}

::v-deep .el-input__inner:hover,
::v-deep .el-cascader:hover .el-input__inner {
  border-color: #8e54e9;
}

::v-deep .el-input__inner:focus,
::v-deep .el-cascader.is-focus .el-input__inner {
  border-color: #4776e6;
  box-shadow: 0 0 0 2px rgba(71, 118, 230, 0.2);
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #8e54e9;
  border-color: #8e54e9;
}

::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #8e54e9;
}

::v-deep .el-checkbox__inner:hover {
  border-color: #8e54e9;
}

/* 按钮容器 */
.button-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 0 20px;
}

.left-buttons, .right-buttons {
  display: flex;
  gap: 10px;
}

/* 表格容器 */
.table-container {
  margin-top: 20px;
  padding: 0 20px 20px;
  background: linear-gradient(to bottom, #fafbfd, #ffffff);
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.tech-table {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

/* 设置表头样式 */
::v-deep .tech-table th {
  background: linear-gradient(to right, #edf1fc, #e0ebfd);
  color: #3a5a97;
  font-weight: 600;
  padding: 12px 8px;
  border-bottom: 2px solid #d8e3f6;
}

/* 设置行样式 */
::v-deep .tech-table td {
  padding: 12px 8px;
  transition: background-color 0.2s;
}

/* 设置产品名称样式 */
.product-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  font-size: 14px;
  line-height: 1.4;
}

.spec-name {
  color: #606266;
  font-size: 12px;
  display: block;
  margin-top: 5px;
}

/* 设置规格信息样式 */
.spec-info {
  background: #f9fafc;
  border-radius: 6px;
  padding: 8px 12px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 5px;
}

.spec-item {
  position: relative;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.spec-label {
  color: #8c8c8c;
  font-size: 12px;
  margin-right: 5px;
  min-width: 70px;
}

.spec-value {
  color: #303133;
  font-size: 12px;
  font-weight: 500;
}

.spec-divider {
  height: 1px;
  background: #ebeef5;
  margin: 5px 0;
}

.highlight-value {
  color: #4776e6;
  font-weight: 600;
}

/* 设置渠道信息样式 */
.channel-info {
  padding: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.channel-item {
  display: flex;
  align-items: center;
  line-height: 1.4;
}

.channel-tag {
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  margin-right: 4px;
  border: 1px solid #d9ecff;
}

.channel-empty {
  color: #909399;
  font-style: italic;
  font-size: 12px;
}

.channel-icon {
  margin-right: 6px;
  color: #909399;
  font-size: 14px;
}

/* 设置价格容器样式 */
.price-container {
  position: relative;
  padding: 5px 8px;
  background: #fff9f9;
  border-radius: 6px;
  border: 1px solid #ffeded;
}

.price-value {
  font-weight: 600;
  color: #f56c6c;
  font-size: 16px;
  text-shadow: 0 1px 0 rgba(0,0,0,0.05);
}

.price-empty {
  color: #909399;
  font-size: 13px;
}

.edit-price-btn {
  position: absolute;
  top: 50%;
  right: 5px;
  transform: translateY(-50%);
  opacity: 0;
  transition: all 0.2s;
}

::v-deep .el-table__row:hover .edit-price-btn {
  opacity: 1;
  right: 10px;
}

/* Action button styling */
.action-btn {
  margin: 0 2px;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* 标签页样式 */
::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  font-size: 14px;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

::v-deep .el-tabs__item.is-active {
  color: #4776e6;
  font-weight: 600;
}

::v-deep .el-tabs__active-bar {
  background-color: #4776e6;
  height: 3px;
  border-radius: 3px;
}

/* 对话框样式 */
::v-deep .el-dialog__header {
  background: linear-gradient(to right, #f7f9fc, #eef2f9);
  padding: 15px 20px;
  border-bottom: 1px solid #e8eaec;
}

::v-deep .el-dialog__title {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
  display: flex;
  align-items: center;
}

::v-deep .el-dialog__headerbtn {
  top: 15px;
  right: 20px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #e8eaec;
  background: #f7f9fc;
}

/* 价格编辑对话框 */
.price-edit-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.price-edit-content {
  padding: 10px 0;
}

.price-table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 15px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 15px;
}

.price-product-info {
  display: flex;
  flex-direction: column;
}

.price-product-name {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  margin-bottom: 5px;
}

.price-product-specs {
  font-size: 12px;
  color: #606266;
}

.price-input-wrapper {
  display: flex;
  align-items: center;
}

.price-input {
  width: 120px;
}

.price-unit {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .search-field {
    min-width: 220px;
  }
}

@media screen and (max-width: 992px) {
  .search-field {
    flex-basis: calc(50% - 10px);
    min-width: auto;
  }
}

@media screen and (max-width: 768px) {
  .search-field {
    flex-basis: 100%;
  }
  
  .button-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .left-buttons, .right-buttons {
    justify-content: flex-start;
  }
}

/* Fix dialog reopening bug by fixing handlers */

/* Enhanced table header styling */
.custom-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-icon {
  margin-right: 5px;
  font-size: 16px;
  color: #4776e6;
}

/* Enhanced product styling */
.product-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  line-height: 1.4;
  position: relative;
  padding-left: 8px;
}

.product-name::before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 3px;
  background: linear-gradient(to bottom, #4776e6, #8e54e9);
  border-radius: 3px;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 3px;
}

/* Enhanced specs styling */
.spec-info {
  background: #f9fafc;
  border-radius: 6px;
  padding: 8px 12px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 5px;
}

.spec-item {
  position: relative;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.spec-label {
  color: #8c8c8c;
  font-size: 12px;
  margin-right: 5px;
  min-width: 70px;
}

.spec-value {
  color: #303133;
  font-size: 12px;
  font-weight: 500;
}

.spec-divider {
  height: 1px;
  background: #ebeef5;
  margin: 5px 0;
}

.highlight-value {
  color: #4776e6;
  font-weight: 600;
}

/* Enhanced channel styling */
.channel-info {
  padding: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.channel-item {
  display: flex;
  align-items: center;
  line-height: 1.4;
}

.channel-tag {
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  margin-right: 4px;
  border: 1px solid #d9ecff;
}

.channel-empty {
  color: #909399;
  font-style: italic;
  font-size: 12px;
}

.channel-icon {
  margin-right: 6px;
  color: #909399;
  font-size: 14px;
}

/* Image placeholder */
.image-placeholder {
  width: 80px;
  height: 80px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 24px;
  border: 1px dashed #dcdfe6;
}

/* Enhanced price container */
.price-container {
  position: relative;
  padding: 5px 8px;
  background: #fff9f9;
  border-radius: 6px;
  border: 1px solid #ffeded;
}

.price-value {
  font-weight: 600;
  color: #f56c6c;
  font-size: 16px;
  text-shadow: 0 1px 0 rgba(0,0,0,0.05);
}

.price-empty {
  color: #909399;
  font-size: 13px;
}

.edit-price-btn {
  position: absolute;
  top: 50%;
  right: 5px;
  transform: translateY(-50%);
  opacity: 0;
  transition: all 0.2s;
}

::v-deep .el-table__row:hover .edit-price-btn {
  opacity: 1;
  right: 10px;
}

/* Action button styling */
.action-btn {
  margin: 0 2px;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
  overflow: hidden;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6ebf5;
}

.filter-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.filter-title i {
  font-size: 18px;
  margin-right: 8px;
  color: #409EFF;
}

.filter-expand-btn {
  font-size: 14px;
  color: #606266;
}

.filter-expand-btn:hover {
  color: #409EFF;
}

.filter-content {
  padding: 20px;
  background-color: #fff;
}

.filter-form {
  margin-bottom: 15px;
}

.filter-cascader,
.filter-select {
  width: 220px;
}

.price-range {
  display: flex;
  align-items: center;
}

.price-input {
  width: 100px;
}

.price-separator {
  margin: 0 8px;
  color: #909399;
}

.active-filters {
  background-color: #f0f9eb;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.active-filters-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #67c23a;
  font-weight: 500;
}

.active-filters-title i {
  margin-right: 8px;
}

.active-filters-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-actions-bar {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.filter-summary {
  margin-left: 20px;
  font-size: 14px;
  color: #606266;
}

.filter-summary strong {
  color: #409EFF;
  font-weight: 600;
}
</style>